iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0
Vue.js

遊戲活動關卡查詢網站系列 第 14

遊戲活動關卡查詢網站Day14-顯示副本資訊2(Vue:Props)

  • 分享至 

  • xImage
  •  

目標
上一篇有提到B組件透過emit的方式傳給父組件
這篇會解說 父組件再將資料傳給C組件的方式

步驟
1.
接下來,父組件要把東西傳給C組件
在C組件中,我們需要定義props去接收父組件傳來的東西
C組件的script需要調整如下

<script setup>
/* global defineProps */
import { ref,computed } from "vue";
const images = require.context('@/assets/Event', false, /\.png$/)

//父組件傳過來的活動副本資訊
const props = defineProps({
  msg: Object
})

//若父組件傳過來的資料為空 則不顯示 傳回false
const showActionList = computed(() => {
  return (!Array.isArray(props.msg?.info) || props.msg.info.length === 0)
  ? false 
  : true;
})

const eventList = computed(() => {
	if (!Array.isArray(props.msg?.info) || props.msg.info.length === 0) {
		return [];
	}

	const result = Object.values(
	props.msg.info.reduce((acc, cur) => {
		const key = cur.eventNo;
		if (!acc[key]) {
			acc[key] = {
			eventNo: cur.eventNo,
			eventName: cur.eventName, 
			eventInfo: []
			};
		}
		
		const info = cur.stagePrimaryNo + cur.stageSecNo;
		if (!acc[key].eventInfo.includes(info)) {
		acc[key].eventInfo.push(info);
		}
		return acc;
	}, {})
	);
	
	return result;
})

function getImg(eventNo) {
  return images(`./E${eventNo}.png`)
}
</script>

eventList利用即時計算的特性
將資料做活動編號的分類
使下圖的資料格式

依序做下面兩個階段處理
先整理為活動編號對應的物件

接著再以Object.keys
整理為依據活動編號分組的陣列

然後我們在C組件的template
補上圖片以及剛才處理過的資料eventList

<template>
<div v-if="showActionList">
	<div class="row">副本一覽</div>
	<div class="row mb-5"  v-for="item in eventList" :key="item.eventNo">
		<div class="col-9">
			<img :src="getImg(item.eventNo)" style="width:100%;">
		</div>
		<div class="col-3">
			<div class="card" >
				<div class="card-header">
					{{item.eventName}}
				</div>
				<ul class="list-group list-group-flush">
					<li class="list-group-item" v-for="child in item.eventInfo" :key="child">
					{{ String(parseInt(child.substring(0,2))).padStart(2, ' ')}}
						-
					{{ String(parseInt(child.substring(2,4))).padStart(2, ' ')}}
					</li>
				</ul>
			</div>
		</div>
	</div>
	
</div>
<div v-else>請先選擇上述活動</div>
</template>

整個過程是,B組件按下圖片後把資料傳給父組件再傳給C組件
而C組件印出副本列表 這個功能就完成了。

由於副本資訊底下會有關卡(例如5-1、5-2)
當我們按「5-1」時,會將「5-1關」敵人資訊代到A組件
這部份留到明天繼續說明。


備註
1.
showActionList這個屬性的目的
因為判斷是否父組件傳過來的東西是空的
如果是空的 則會提示使用者點擊上面圖片

最後復盤這兩篇篇做的事情
●點擊B組件的圖片 ->B組件透過emit,把資料傳給父組件
透過監聽response接收,存給B_msg
●父組件傳資料給C組件->透過綁定msg將B_msg傳入
接著C組件透過props接收
●C組件呈現資料判斷 ->一開始因為沒有選活動,所以父組件傳過來的會是空陣列物件
我們需要Computed屬性去判斷
如果沒選,就提示使用者選
如果有選,就呈現副本列表

下面附上完整資料的流動 如下圖


上一篇
遊戲活動關卡查詢網站Day13-顯示副本資訊1(Vue:Emits)
下一篇
遊戲活動關卡查詢網站Day15-敵人資訊1(Vue:Watch)
系列文
遊戲活動關卡查詢網站23
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言